import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:zootix/models/zt_rank_account.model.dart';
import 'package:zootix/apis/zt-api.dart' as Api;
import 'package:zootix/screens/goods/zt_goods_controller.dart';
import 'package:zootix/screens/goods/zt_goods_popup.dart';
import 'package:zootix/screens/rank/zt_buy_confirm_popup.dart';
import 'package:zootix/screens/rank/zt_ticket_number_popup.dart';
import 'package:zootix/services/zt_purchase.service.dart';
import 'package:zootix/services/zt_service.dart';
import 'package:zootix/store/zt_store.dart';
import 'package:zootix/util/zt_convert.dart';
import 'package:zootix/widgets/zt_fade_in_cache_image.dart';

import '../../constants/zt_constants.dart';
import '../../util/zt_util.dart';

class ZtRankController extends GetxController {
  final rankList = RxList<RankAccount>([]);
  late String parkType = '';
  int ticketPrice = 0;

  @override
  onReady() {
    getRankList();
    ticketPrice = ZtData.rankTicketPrice[parkType]!;
    super.onReady();
  }

  Future<void> goPriviateChat(int index) async {
    await showDialog(
        context: Get.context!,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10), // 设置圆角半径为10
              ),
              contentPadding: const EdgeInsets.all(10),
              content: Row(
                children: [
                  Container(
                    clipBehavior: Clip.hardEdge,
                    decoration: const BoxDecoration(
                      shape: BoxShape.circle,
                    ),
                    width: ZtScreenAdaper.width(40),
                    child: ZtFadeInCacheImage(
                      width: ZtScreenAdaper.width(40),
                      url: rankList[index].avatar,
                    ),
                  ),
                  SizedBox(
                    width: ZtScreenAdaper.width(5),
                  ),
                  Expanded(
                      child: Text(
                    '${rankList[index].nickname}',
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        fontSize: ZtScreenAdaper.sp(15),
                        fontWeight: FontWeight.w500),
                  )),
                  SizedBox(
                    width: ZtScreenAdaper.width(5),
                  ),
                  ElevatedButton(
                      style: ElevatedButton.styleFrom(
                          shape: RoundedRectangleBorder(
                              borderRadius:
                                  BorderRadius.circular(ZtScreenAdaper.sp(30))),
                          padding: EdgeInsets.symmetric(
                              horizontal: ZtScreenAdaper.height(15),
                              vertical: ZtScreenAdaper.height(5)),
                          backgroundColor: const Color(0xFFFFCA41)),
                      onPressed: () {
                        Get.back();
                        Get.toNamed(ZtRouteConfig.privateChat, arguments: {
                          'nickname': rankList[index].nickname,
                          'userId': rankList[index].userId,
                          'avatar': rankList[index].avatar,
                        });
                      },
                      child: Row(
                        children: [
                          Image(
                            height: ZtScreenAdaper.width(20),
                            image: const AssetImage(
                                'assets/images/rank_chat_icon.png'),
                          ),
                          SizedBox(
                            width: ZtScreenAdaper.width(5),
                          ),
                          Text(
                            'Chat',
                            style: TextStyle(fontSize: ZtScreenAdaper.sp(15)),
                          )
                        ],
                      ))
                ],
              ));
        });
  }

  Future<void> getRankList() async {
    await ZtLoadingUtil.show(status: 'Loading...');
    try {
      final history =
          ZtStorageService.to.getString(ZtCacheKeys.rankList, isWithUser: true);
      if (history != null) {
        List<dynamic>? currentParkTypeRankList = jsonDecode(history)?[parkType];
        if (currentParkTypeRankList != null) {
          List<String> blockIds = ZtBlockStore.to.blockList
              .map((element) => '${element.broadcasterId}')
              .toList();
          currentParkTypeRankList.removeWhere((element) =>
              blockIds.contains(element['userId'].toString()) ||
              element['userId'] == ZtAuthStore.to.userInfo.value.userId);
          rankList.assignAll(toList(currentParkTypeRankList)
              .map((e) => RankAccount.fromJson(e))
              .toList());
          return;
        }
      }
      final response = await Api.getRankList();
      rankList.clear();
      if (response.data != null) {
        final result = toList(response.data['data'])
            .map((e) => RankAccount.fromJson(e))
            .toList();
        Map<String, List<RankAccount>> newRankList = {};
        if (history != null) {
          final historyMap = jsonDecode(history);
          historyMap[parkType] = result;
          await ZtStorageService.to.setString(
              ZtCacheKeys.rankList, jsonEncode(historyMap),
              isWithUser: true);
        } else {
          newRankList[parkType] = result;
          await ZtStorageService.to.setString(
              ZtCacheKeys.rankList, jsonEncode(newRankList),
              isWithUser: true);
        }
        rankList.addAll(result);
      }
    } catch (e) {
      ZtSnackBarUtil().error('$e');
    } finally {
      await EasyLoading.dismiss();
    }
  }

  Future<void> asyncRankListFollowed(String userId, bool isFollowed) async {
    List<String> parkTypeList = [
      'elephant',
      'deer',
      'raccoon',
      'swan',
      'squirrel'
    ];
    String? rankList =
        ZtStorageService.to.getString(ZtCacheKeys.rankList, isWithUser: true);

    if (rankList != null) {
      Map history = jsonDecode(rankList);
      parkTypeList.forEach((element) {
        if (history[element] != null) {
          history[element] = history[element].map((item) {
            if (item['userId'] == userId) {
              item['isFriend'] = isFollowed;
            }
            return item;
          }).toList();
        }
      });

      await ZtStorageService.to.setString(
          ZtCacheKeys.rankList, jsonEncode(history),
          isWithUser: true);
    }
  }

  Future<void> addFriend(String userId, int index) async {
    await ZtLoadingUtil.show(status: 'Loading...');
    try {
      final response = await Api.addFriend(userId);
      if (response.data != null) {
        rankList[index].isFriend = true;
        Map history = jsonDecode(ZtStorageService.to
            .getString(ZtCacheKeys.rankList, isWithUser: true)!);
        history[parkType] = rankList;
        await ZtStorageService.to.setString(
            ZtCacheKeys.rankList, jsonEncode(history),
            isWithUser: true);
        rankList.refresh();
        ZtSnackBarUtil().success('Follow successfully!');
      }
    } catch (e) {
    } finally {
      await EasyLoading.dismiss();
    }
  }

  Future confirmBuyCoin() async {
    ZtLogManger().putLog(
      ZtLogType.clickEvent,
      ZtLogManger.buildEvent(
          logType: ZtLogType.clickEvent, page: ZtLogPages.purchase),
    );
    await showDialog(
        context: Get.context!,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(30), // 设置圆角半径为10
            ),
            contentPadding: const EdgeInsets.all(0),
            content: ZtBuyConfirmPopup(parkType: parkType),
          );
        });
  }

  Future doPurchase() async {
    if ((ZtAuthStore.to.userInfo.value.availableCoins ?? 0) < ticketPrice) {
      Get.bottomSheet(ZtGoodsPopup()).then((value) {
        Get.delete<ZtGoodsController>();
      });
    } else {
      await ZtPurchaseService.to.consumeCoin(ticketPrice);
      Get.back();
      ZtAuthStore.to.userInfo.value.availableCoins =
          (ZtAuthStore.to.userInfo.value.availableCoins ?? 0) - ticketPrice;
      ZtAuthStore.to.userInfo.refresh();
      await ZtTicketStore.to.generateTicketNumber(parkType);
      await showDialog(
          context: Get.context!,
          barrierDismissible: true,
          builder: (BuildContext context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30), // 设置圆角半径为10
              ),
              contentPadding: const EdgeInsets.all(0),
              content: ZtTicketNumberPopup(),
            );
          });
    }
  }
}
